﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    [Authorization]
    public class ShopsController : BaseController
    {
        private readonly ShopsBLL _bll = new ShopsBLL();

        #region 列表

        public ActionResult List()
        {
            if (!CurrentUser.IsHeadquarters)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult Listing(int draw, int start, int length)
        {
            if (!CurrentUser.IsHeadquarters)
            {
                return Json(null);
            }
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            string direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "Name", "LegalPerson", "LegalPersonMobile", "Address", "Description", "IsActive", "Id" };
            string search = Request["search[value]"];
            int pageIndex = (start / length) + 1;

            TableDataViewDto<ViewShopsDto> theList = _bll.GetPagingList(draw, pageIndex, length, SqlSafe(search), orderByColumns[order] + " " + direction, null, CurrentUser.ShopId);

            JsonResult jsonResult = Json(theList);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }

        [HttpPost]
        public JsonResult GetBranchShopList(string keyWords)
        {
            return Json(CurrentUser.IsHeadquarters ? ShopsBLL.Instance.GetBranchShopList(keyWords, CurrentUser.ShopId) : null);
        }

        [HttpPost]
        public JsonResult GetActiveShopList(string keyWords)
        {
            return Json(ShopsBLL.Instance.GetListByName(keyWords, true));
        }

        #endregion

        [PermissionFilter]
        public ActionResult Update(int id = 0)
        {
            InitiSet();
            if (id <= 0 || !CurrentUser.IsHeadquarters)
            {
                id = CurrentUser.ShopId;
            }
            else
            {
                var checkModel = ShopsBLL.Instance.GetModelList("Id=" + id + " and ParentShopId=" + CurrentUser.ShopId);
                if (checkModel.Count == 0)
                {
                    id = CurrentUser.ShopId;
                }
            }
            var model = _bll.GetModel(id);
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);
            }
            if (!string.IsNullOrEmpty(model.Longitude) && !string.IsNullOrEmpty(model.Latitude))
            {
                var coordinateStr = CoordinateTransform.WG84_BD(Convert.ToDouble(model.Longitude), Convert.ToDouble(model.Latitude));
                model.Longitude = coordinateStr[0].ToString();
                model.Latitude = coordinateStr[1].ToString();
            }
            ViewBag.theLogo = ConfigurationManager.AppSettings["ImgFileSitePath"] + model.Logo;
            return View(model);
        }
        [HttpPost]
        public ActionResult Update(FormCollection collection, Shops model)
        {
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (model.Id != CurrentUser.ShopId)
            {
                if (CurrentUser.IsHeadquarters)
                {
                    var checkModel =
                        ShopsBLL.Instance.GetModelList("Id=" + model.Id + " and ParentShopId=" + CurrentUser.ShopId);
                    if (checkModel.Count == 0)
                    {
                        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                    }
                }
                else
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
            }
            var tempModel = ShopsBLL.Instance.GetModelByName(model.Name);
            if (tempModel != null && tempModel.Id != model.Id)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (model.BusinessStatus == 1)
            {
                model.CloseTimeStart = DateTime.Now;
                model.CloseTimeEnd = DateTime.Now;
            }

            string strUploadImage = UploadImage("fileImage", "/Shops/Logo/", 300, 300);
            if (!string.IsNullOrEmpty(strUploadImage)) model.Logo = strUploadImage;

            Shops oriModel = _bll.GetModel(model.Id);
            if (string.IsNullOrEmpty(model.Address))
            {
                model.Address = oriModel.Address;
            }
            if (oriModel.CanFrontView)
            {
                model.CanFrontView = true;
            }
            if (oriModel.Longitude != model.Longitude || oriModel.Latitude != model.Latitude)
            {
                var coordinateStr = CoordinateTransform.BD_WG84(Convert.ToDouble(model.Longitude), Convert.ToDouble(model.Latitude));
                model.Longitude = coordinateStr[0].ToString();
                model.Latitude = coordinateStr[1].ToString();
                model.IsCoordinateTransform = true;
            }
            model.IsHeadquarters = oriModel.IsHeadquarters;
            model.ParentShopId = oriModel.ParentShopId;

            model.UpdatedBy = CurrentUser.AccountId;
            model.Updated = DateTime.Now;

            bool result = _bll.Update(model);

            if (result)
            {
                if (model.Id == CurrentUser.ShopId)
                {
                    return RedirectToAction("Update", "Shops");
                }
                else
                {
                    return RedirectToAction("List", "Shops");
                }
            }

            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        /// <summary>
        /// 检查店铺名称是否已被使用
        /// </summary>
        /// <remarks>2016-08-31 万乐园 创建</remarks>
        [HttpPost]
        public JsonResult CheckShopName(int id, string name)
        {
            var result = true;
            var tempModel = ShopsBLL.Instance.GetModelByName(name);
            if (tempModel != null && tempModel.Id != id)
            {
                result = false;
            }
            return Json(result);
        }

        #region Private Functions 自用函数

        private void InitiSet()
        {
            var lsBusinessStatus = new List<SelectListItem>
            {
                new SelectListItem {Value = "1", Text = "营业中"},
                new SelectListItem {Value = "2", Text = "打烊"}
            };
            ViewBag.lsBusinessStatus = lsBusinessStatus;
        }

        #endregion
    }
}